package com.hong.spring.grpc;

import com.hong.spring.common.GrpcService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
/**
 *
 * 功能描述: 服务端
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2021/1/27 11:45
 */
@Log4j2
@GrpcService
public class GrpcServer {

    private Server server;

    private int port;

    public GrpcServer(int port) {
        this.port = port;
    }

    public void start() throws IOException, InterruptedException {
        new Thread(()->{
            //启动服务端
            try {
                ServerBuilder.forPort(port)
                        // 将具体实现的服务添加到gRPC服务中
                        .addService(new HelloWorldRpcService())
                        .build().start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 添加服务端关闭的逻辑
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("Shutting down gRPC server.");
            this.shutdown();
            log.info("gRPC server shut down successfully.");
        }));
        //this.block();
    }

    public void shutdown() {
        if (server != null) {
            server.shutdown();
        }

    }

    public void block() throws InterruptedException {
        if (server != null) {
            // 服务端启动后直到应用关闭都处于阻塞状态，方便接收请求
            server.awaitTermination();
        }
    }
}